<?php

namespace App\Library\Service;

use App\Library\Logic\OperateLogLogic;
use App\Library\Logic\ShopHandbookLogic;
use App\Library\Requests\Base\SerialNumberRequest;
use App\Library\Requests\Handbook\HandbookAddRequest;
use App\Library\Requests\Handbook\HandbookEditRequest;
use App\Library\Requests\Handbook\HandbookPageRequest;
use Illuminate\Http\JsonResponse;

class HandbookService extends BaseService
{
    /**
     * @param ShopHandbookLogic $logic
     */
    public function __construct(ShopHandbookLogic $logic)
    {
        $this->logic = $logic;
    }

    /**
     * paging
     * @param HandbookPageRequest $request
     * @return JsonResponse
     */
    public function paging(HandbookPageRequest $request): JsonResponse
    {
        return success($this->logic->paging($request));
    }

    /**
     * add
     * @param HandbookAddRequest $request
     * @return JsonResponse
     */
    public function add(HandbookAddRequest $request): JsonResponse
    {
        $this->logic->insertForModel(array_merge($this->logic->saveCom($request), [
            'userId' => USERID,
            'createdAt' => time(),
        ]));
        OperateLogLogic::add();
        return success();
    }

    /**
     * edit
     * @param HandbookEditRequest $request
     * @return JsonResponse
     */
    public function edit(HandbookEditRequest $request): JsonResponse
    {
        $model = $this->logic->findBySerialNumber($request);
        if (is_null($model) || $model->user_id !== USERID) return fail(433);
        $this->logic->updateForModel($this->logic->saveCom($request), $model);
        OperateLogLogic::add();
        return success();
    }

    /**
     * detail
     * @param SerialNumberRequest $request
     * @return JsonResponse
     */
    public function detail(SerialNumberRequest $request): JsonResponse
    {
        $model = $this->logic->findBySerialNumber($request);
        if (is_null($model)) return fail(433);
        $model->my = $model->user_id === USERID;
        return success($model);
    }

    /**
     * delete
     * @param SerialNumberRequest $request
     * @return JsonResponse
     */
    public function delete(SerialNumberRequest $request): JsonResponse
    {
        $model = $this->logic->findBySerialNumber($request);
        if (is_null($model) || $model->user_id !== USERID) return fail(433);
        $model->delete();
        OperateLogLogic::add();
        return success();
    }
}
